import sys

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QMessageBox

from FlowControl.utils import *


class MainWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.light_boxes = list()

        self.setWindowTitle('流控模拟器')
        self.add_button = QtWidgets.QPushButton('添加计划')
        self.preview_button = QtWidgets.QPushButton("报文预览")
        self.send_button = QtWidgets.QPushButton("发送流控")

        self.set_global_flow_control = QtWidgets.QPushButton("全局流控设置")

        self.h_light = QtWidgets.QHBoxLayout()
        self.layout = QtWidgets.QVBoxLayout()

        self.init_ui()
        self.init_connect()

    def init_ui(self):
        """
        初始化UI
        @return:
        """
        self.h_light.addWidget(self.send_button)
        self.h_light.addWidget(self.preview_button)
        self.h_light.addWidget(self.add_button)
        self.h_light.addWidget(self.set_global_flow_control)

        self.layout.addLayout(self.h_light)
        self.setLayout(self.layout)

    def init_connect(self):
        """
        初始化信号连接
        @return:
        """
        self.add_button.clicked.connect(self.add_light_box)
        self.send_button.clicked.connect(self.send_flow_control)
        self.preview_button.clicked.connect(self.message_preview)
        self.set_global_flow_control.clicked.connect(self.set_global_flow_control_box)

    def add_light_box(self):
        """
        添加计划
        @return:
        """
        light_box = UILightBox()
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(light_box)

        self.light_boxes.append(light_box)
        self.layout.addLayout(layout)

    def remove_light_box(self, light_box):
        """
        删除计划
        @param light_box:
        @return:
        """
        self.light_boxes.remove(light_box)
        light_box.deleteLater()

    def message_preview(self):
        """
        报文预览
        @return:
        """
        pass

    def send_flow_control(self):
        """
        发送流控
        @return:
        """
        pass

    def set_global_flow_control_box(self):
        """
        全局流控设置
        @return:
        """
        pass


def on_text_changed(obj_qline_edit: QtWidgets.QLineEdit):
    """
    文本改变
    @param obj_qline_edit:
    @return:
    """
    obj_qline_edit.setText(obj_qline_edit.text().upper())


class UILightBox(QtWidgets.QWidget):
    clicked = QtCore.pyqtSignal()

    def __init__(self, param=None):
        super().__init__(param)
        self.flowWindow = None
        self.label_flight = QtWidgets.QLabel("航班号")
        self.flight = QtWidgets.QLineEdit()
        self.label_sobt = QtWidgets.QLabel("计划撤轮档时间")
        self.sobt = QtWidgets.QLineEdit()
        self.label_DEPAP = QtWidgets.QLabel("起飞机场")
        self.DEPAP = QtWidgets.QLineEdit()
        self.label_ARRAP = QtWidgets.QLabel("目的机场")
        self.ARRAP = QtWidgets.QLineEdit()

        self.flowButton = QtWidgets.QPushButton("设置流控")

        # 删除按钮
        self.delButton = QtWidgets.QPushButton("删除计划")
        # 设置按钮样式
        self.flow_control_completed_label = QtWidgets.QLabel()
        self.flow_control_completed_label.setText("*流控已设置*")
        self.flow_control_completed_label.setStyleSheet("color: red; font-weight: bold")

        self.init_ui()
        self.init_connect()

    def init_ui(self):
        """

        @return:
        """
        box_light = QtWidgets.QHBoxLayout()
        box_light.addWidget(self.label_flight)
        box_light.addWidget(self.flight)
        box_light.addWidget(self.label_sobt)
        box_light.addWidget(self.sobt)
        box_light.addWidget(self.label_DEPAP)
        box_light.addWidget(self.DEPAP)
        box_light.addWidget(self.label_ARRAP)
        box_light.addWidget(self.ARRAP)
        box_light.addWidget(self.flowButton)
        box_light.addWidget(self.delButton)
        box_light.addWidget(self.flow_control_completed_label)

        self.setLayout(box_light)

    def init_connect(self):
        """

        @return:
        """
        self.flight.installEventFilter(self)
        # self.flight.textChanged.connect(on_text_changed)
        self.flowButton.clicked.connect(self.open_flow_control_window)
        self.delButton.clicked.connect(self.removeLightBox)

    def open_flow_control_window(self):
        text = self.flight.text()
        if text:
            self.flowWindow = FlowControlWindow(flight=text, flight_identification="TEST",
                                                ntfm_flight="TEST1")
            self.flowWindow.pysignal.connect(self.flow_control_completed)
            self.flowWindow.show()
        else:
            QMessageBox.warning(self, 'Warning', '未输入航班号！！！')

    def removeLightBox(self):
        self.deleteLater()

    def flow_control_completed(self, flag: bool):
        """
        留空信息填写完成
        @param flag:
        @return:
        """
        if flag:
            # 变绿
            self.flow_control_completed_label.setStyleSheet("color: green; font-weight: bold")

    def mousePressEvent(self, event):
        """
        重写
        @return:
        """
        if event.button() == 1:  # 检查鼠标点击的是左键
            text = self.input_box.text()
            if text:
                print(f"Input box contains: {text}")
            else:
                print("Input box is empty")
        super().mousePressEvent(event)

    def eventFilter(self, source, event):
        if source is self.flight and event.type() == QtCore.QEvent.KeyPress:
            key = event.key()
            if QtCore.Qt.Key_A <= key <= QtCore.Qt.Key_Z:
                text = self.flight.text() + QtGui.QKeySequence(key).toString()
                self.flight.setText(text.upper())
                return True
        return super().eventFilter(source, event)


class FlowControlWindow(QtWidgets.QWidget):
    pysignal = QtCore.pyqtSignal(bool)

    def __init__(self, flight: str, flight_identification: str, ntfm_flight: str):
        super().__init__()

        self.flow_item = None  # 流控信息
        self.flight_identification = flight_identification
        self.ntfm_flight = ntfm_flight

        self.setWindowTitle(F"航班{flight}流控信息设置")
        self.setGeometry(100, 100, 400, 200)

        self.label_PRIORITY = QtWidgets.QLabel("航班优先级")
        self.priority = QtWidgets.QComboBox()
        self.priority_options = {"正常": 0,
                                 "航空公司协调": 10,
                                 "国内转国际": 30,
                                 "国际": 40,
                                 "豁免": 48,
                                 "要客": 50}
        # 添加值和对应的中文意思
        self.priority.addItems(self.priority_options.keys())

        self.label_AOBT = QtWidgets.QLabel("实际推出/撤轮档时间")
        self.aobt = QtWidgets.QDateTimeEdit()
        self.aobt.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_TOBT = QtWidgets.QLabel("目标撤轮档时间")
        self.tobt = QtWidgets.QDateTimeEdit()
        self.tobt.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_cobt = QtWidgets.QLabel("计算撤轮档时间")
        self.cobt = QtWidgets.QDateTimeEdit()
        self.cobt.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_ctot = QtWidgets.QLabel("计算起飞时间")
        self.ctot = QtWidgets.QDateTimeEdit()
        self.ctot.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_ctot_source = QtWidgets.QLabel("CTOT来源")
        self.ctot_source = QtWidgets.QComboBox()
        self.ctot_source.addItems(["CDM", "CRS", "NTFM"])

        self.label_cobt_type = QtWidgets.QLabel("COBT类型")
        self.cobt_type = QtWidgets.QComboBox()
        self.cobt_type.addItems(["0", "100", "200", "300", "400", "500", "600", "700"])

        self.label_ctot_compliant = QtWidgets.QLabel("计算起飞时间")
        self.ctot_compliant = QtWidgets.QComboBox()
        self.ctot_compliant.addItems(["0", "100"])

        self.label_asbt = QtWidgets.QLabel("实际上客时间")
        self.asbt = QtWidgets.QDateTimeEdit()
        self.asbt.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_agct = QtWidgets.QLabel("实际关舱门时间")
        self.agct = QtWidgets.QDateTimeEdit()
        self.agct.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_position = QtWidgets.QLabel("使用停机位")
        self.position = QtWidgets.QLineEdit()
        # 只能输出数字
        self.position.setValidator(QtGui.QIntValidator())

        self.label_contrl_status = QtWidgets.QLabel("受控状态")
        self.contrl_status = QtWidgets.QComboBox()
        self.contrl_status.addItems(["0", "100"])

        self.label_hobt = QtWidgets.QLabel("协调撤轮档时间")
        self.hobt = QtWidgets.QDateTimeEdit()
        self.hobt.setDisplayFormat("yyyy-MM-dd HH:mm")  # 设置显示格式

        self.label_hit_flowcontrols = QtWidgets.QLabel("命中流控")
        self.hit_flowcontrols = QtWidgets.QLineEdit()

        self.label_hit_flowcontrols_his = QtWidgets.QLabel("命中流控历史")
        self.hit_flowcontrols_his = QtWidgets.QLineEdit()

        self.label_executedate = QtWidgets.QLabel("执行日期")
        self.executedate = QtWidgets.QDateEdit()
        self.executedate.setDisplayFormat("yyyy-MM-dd")

        self.save_button = QtWidgets.QPushButton("保存")

        self.init_ui()
        self.init_connect()

    def init_ui(self):
        """
        设置布局
        @return:
        """
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.label_PRIORITY)
        layout.addWidget(self.priority)
        layout.addWidget(self.label_AOBT)
        layout.addWidget(self.aobt)
        layout.addWidget(self.label_TOBT)
        layout.addWidget(self.tobt)
        layout.addWidget(self.label_cobt)
        layout.addWidget(self.cobt)
        layout.addWidget(self.label_ctot)
        layout.addWidget(self.ctot)
        layout.addWidget(self.label_ctot_source)
        layout.addWidget(self.ctot_source)
        layout.addWidget(self.label_cobt_type)
        layout.addWidget(self.cobt_type)
        layout.addWidget(self.label_ctot_compliant)
        layout.addWidget(self.ctot_compliant)
        layout.addWidget(self.label_asbt)
        layout.addWidget(self.asbt)
        layout.addWidget(self.label_agct)
        layout.addWidget(self.agct)
        layout.addWidget(self.label_position)
        layout.addWidget(self.position)
        layout.addWidget(self.label_contrl_status)
        layout.addWidget(self.contrl_status)
        layout.addWidget(self.label_hobt)
        layout.addWidget(self.hobt)
        layout.addWidget(self.label_hit_flowcontrols)
        layout.addWidget(self.hit_flowcontrols)
        layout.addWidget(self.label_hit_flowcontrols_his)
        layout.addWidget(self.hit_flowcontrols_his)
        layout.addWidget(self.label_executedate)
        layout.addWidget(self.executedate)
        layout.addWidget(self.save_button)
        self.setLayout(layout)

    def init_connect(self):
        """
        设置信号连接
        @return:
        """
        self.save_button.clicked.connect(self.save_flow_control)

    def save_flow_control(self):
        """
        保存流控
        @return:
        """
        try:
            print(
                self.flight_identification,
                self.ntfm_flight,
                self.priority_options[self.priority.currentText()]
            )
            hit_flowcontrols: list = list()
            hit_flowcontrols_his: list = list()
            if self.hit_flowcontrols.text() and self.hit_flowcontrols_his.text():
                hit_flowcontrols = self.hit_flowcontrols.text().split(',')
                hit_flowcontrols_his = self.hit_flowcontrols_his.text().split(',')
            print(hit_flowcontrols, hit_flowcontrols_his)
            __flight_identification = self.flight_identification
            __ntfm_flight = self.ntfm_flight,
            __priority = self.priority_options[self.priority.currentText()],
            __aobt = self.aobt.text(),
            __tobt = self.tobt.text(),
            __cobt = self.cobt.text(),
            __ctot = self.ctot.text(),
            __ctot_source = self.ctot_source.currentText(),
            __cobt_type = self.cobt_type.currentText(),
            __ctot_compliant = self.ctot_compliant.currentText(),
            __asbt = self.asbt.text(),
            __agct = self.agct.text(),
            __position = self.position.text(),
            __contrl_status = self.contrl_status.currentText(),
            __hobt = self.hobt.text(),
            __hit_flowcontrols = hit_flowcontrols,
            __hit_flowcontrols_his = hit_flowcontrols_his,
            __executedate = self.executedate.text()

            print(
                __flight_identification,
                self.ntfm_flight,
                __priority,
                __aobt,
                __tobt,
                __cobt,
                __ctot,
                __ctot_source,
                __cobt_type,
                __ctot_compliant,
                __asbt,
                __agct,
                __position,
                __contrl_status,
                __hobt,
                __hit_flowcontrols,
                __hit_flowcontrols_his,
                __executedate
            )
            self.flow_item = format_item(
                self.flight_identification,
                self.ntfm_flight,
                __priority[0],
                __aobt[0],
                __tobt[0],
                __cobt[0],
                __ctot[0],
                __ctot_source[0],
                __cobt_type[0],
                __ctot_compliant[0],
                __asbt[0],
                __agct[0],
                __position[0],
                __contrl_status[0],
                __hobt[0],
                __hit_flowcontrols[0],
                __hit_flowcontrols_his[0],
                __executedate
            )
            self.pysignal.emit(True)
        except Exception as e:
            QMessageBox.warning(self, 'Warning', f'保存流控失败：\n{e}')


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
